import React, { useState } from 'react'
import ReactMarkdown from 'react-markdown'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import {
  materialDark,
  materialLight
} from 'react-syntax-highlighter/dist/esm/styles/prism'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'

import remarkGfm from 'remark-gfm'
import { useTheme } from 'next-themes'

import 'highlight.js/styles/github.css'
import 'katex/dist/katex.min.css'
import 'github-markdown-css'
import './index.css'
import CopyButton from '../CopyButton'

class ReactMarkdownProps {
  code? = '' as any
  isToc? = false as boolean
  id!: string
}
// materialDark,
// materialLight
const styleMd = {
  dark: materialDark,
  light: materialLight
}

const NextMarkdown: React.FC<ReactMarkdownProps> = ({ code, id }) => {
  const { theme } = useTheme() as { theme: string }

  return (
    <div className="flex">
      <div id={id}>
        <ReactMarkdown
          className="markdown-body dark:text-white dark:bg-[#1F2937]"
          remarkPlugins={[remarkMath, remarkGfm]}
          rehypePlugins={[rehypeKatex]}
          components={{
            code({ node, inline, className, children, ...props }) {
              const match = /language-(\w+)/.exec(className || '')
              return match ? (
                <>
                  <div
                    style={{
                      textAlign: 'right'
                    }}
                  >
                    <CopyButton text={String(children).replace(/\n$/, '')} />
                  </div>

                  <SyntaxHighlighter
                    showLineNumbers={true}
                    startingLineNumber={1}
                    language={match[1]}
                    style={!!theme ? styleMd[theme] : styleMd.light}
                    lineNumberStyle={{ color: '#ddd', fontSize: 16 }}
                    wrapLines={false}
                  >
                    {String(children).replace(/\n$/, '')}
                  </SyntaxHighlighter>
                </>
              ) : (
                <code className={className} {...props}>
                  {children}
                </code>
              )
            },
            em: ({ node, ...props }) => (
              <i style={{ color: 'red' }} {...props} />
            )
          }}
        >
          {code}
        </ReactMarkdown>
      </div>
    </div>
  )
}

export default NextMarkdown
